package cn.kent.high.questions.concurrentHashMap;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用 {@link java.util.concurrent.ConcurrentHashMap#putIfAbsent(Object, Object)} 优化多线程下重复k的覆盖问题
 * 该方法 当插入成功，会返回null，否则返回当前k对应的v
 */
public class TestMap2 {
    static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            final ArrayList<String> list1 = new ArrayList<>();
            list1.add("device1");
            list1.add("device2");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if (null != oldList) {
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });
        Thread thread2 = new Thread(() -> {
            final ArrayList<String> list1 = new ArrayList<>();
            list1.add("device11");
            list1.add("device22");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if (null != oldList) {
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });
        Thread thread3 = new Thread(() -> {
            final ArrayList<String> list1 = new ArrayList<>();
            list1.add("device111");
            list1.add("device222");
            List<String> oldList = map.putIfAbsent("topic2", list1);
            if (null != oldList) {
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
